package com.ugoodtech.mdcc.web.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.domain.Feedback;
import com.ugoodtech.mdcc.core.domain.QFeedback;
import com.ugoodtech.mdcc.core.repository.UserRepository;
import com.ugoodtech.mdcc.core.repository.FeedbackRepository;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.service.FeedBackService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class FeedBackServiceImpl implements FeedBackService {

    @Autowired
    private FeedbackRepository feedbackRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 意见管理-获得所有/条件搜索
     *
     * @param userId     用户ID
     * @param username   姓名
     * @param suggestion 意见内容
     * @param pageable
     * @return
     */
    @Override
    public JsonResponse getAllFeedBack(Long userId, String username, String suggestion, Pageable pageable) {
        QFeedback qFeedback = QFeedback.feedback;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(builder.and(qFeedback.deleted.eq(false)));
        if (userId != null && userId != 0L) {
            User user = userRepository.findOne(userId);
            if (user != null) {
                builder.and(qFeedback.user.id.eq(userId));
            } else {
                return JsonResponse.errorResponseWithError("500", "此ID用户未找到");
            }
        }
        if (StringUtils.isNotEmpty(username)) {
            User user = userRepository.findByUsername(username);
            if (user != null) {
                builder.and(qFeedback.user.username.eq(username));
            } else {
                return JsonResponse.errorResponseWithError("500", "此用户名字未找到");
            }
        }
        if (StringUtils.isNotEmpty(suggestion)) {
            builder.and(qFeedback.suggestion.like("%" + suggestion + "%"));
        }
        Page<Feedback> page = feedbackRepository.findAll(builder, pageable);
        return JsonResponse.successResponseWithPageData(page);
    }

}
